package com.longjianghuasheng.logistics.business.order.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.TimeUtils
import com.longjianghuasheng.logistics.R
import com.longjianghuasheng.logistics.base.BaseTitleFragment
import com.longjianghuasheng.logistics.business.detail.WarehousingAdapter
import com.longjianghuasheng.logistics.business.order.adapter.FlowTagOrderDetailAdapter
import com.longjianghuasheng.logistics.business.order.adapter.LocusAdapter
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_CANCEL
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_CONFIRM_COMPLETED
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_CONFIRM_THE_RECEIPT_OF_GOODS
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_DELETE
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_PAYMENT
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_SIGNED
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_SIGN_UP_ENTRANCE
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.BT_TRAJECTORY
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.STATUS_COMPLETED
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.STATUS_FOR_THE_PAYMENT
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.STATUS_TO_SIGN_UP
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.STATUS_TO_START
import com.longjianghuasheng.logistics.business.order.adapter.OrderAdapter.Companion.STATUS_UNDERWAY
import com.longjianghuasheng.logistics.business.order.viewmodel.OrderDetailViewModel
import com.longjianghuasheng.logistics.business.order.viewmodel.OrderViewModel
import com.longjianghuasheng.logistics.data.model.bean.ApiResponseNoData
import com.longjianghuasheng.logistics.databinding.FragmentOrderDetailBinding
import com.longjianghuasheng.logistics.entity.OrderDetailResponse
import com.longjianghuasheng.logistics.eventViewModel
import com.longjianghuasheng.logistics.ext.*
import com.longjianghuasheng.logistics.util.CacheUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.view.gone
import me.hgj.jetpackmvvm.ext.view.visible

class OrderDetailFragment :
    BaseTitleFragment<OrderDetailViewModel, FragmentOrderDetailBinding>() {

    private val warehousingAdapter by lazy {
        WarehousingAdapter()
    }

    private val locationAdapter by lazy {
        WarehousingAdapter()
    }

    private val locusAdapter by lazy {
        LocusAdapter()
    }
    private val flowTagAdapter by lazy {
        FlowTagOrderDetailAdapter(context)
    }
    private val orderViewModel by viewModels<OrderViewModel>()

    override fun layoutId(): Int = R.layout.fragment_order_detail

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initTitleBar("订单详情")
        mDatabind.initListener()


    }

    //
    private fun FragmentOrderDetailBinding.initListener() {


        stvLocusTitle.setRightImageViewClickListener {

            showQrCodeDialog(mViewModel.ewm)
        }

        flowlayout.adapter = flowTagAdapter

        flowTagAdapter.onClickListener = {

            when (it) {

                BT_SIGN_UP_ENTRANCE -> navigate(R.id.signUpFragment, Bundle().apply {
                    putInt("id", mViewModel.id)
                })
                BT_CANCEL -> hintDialog("确定取消吗？", {
                    orderViewModel.order_del()
                })
                BT_SIGNED -> navigate(R.id.signUpFragment, Bundle().apply {
                    putInt("id", mViewModel.id)
                })
                BT_PAYMENT -> {}
                BT_TRAJECTORY -> navigate(R.id.orderDetailFragment, Bundle().apply {
                    putInt("id", mViewModel.id)

                })
                BT_DELETE -> deleteDialog {
                    orderViewModel.order_del()
                }
                BT_CONFIRM_COMPLETED, BT_CONFIRM_THE_RECEIPT_OF_GOODS -> {
                    orderViewModel.order_done()
                }
                else -> {}
            }
        }

        locusAdapter.run {


            addChildClickViewIds(R.id.tv_remark)
            setOnItemChildClickListener { adapter, view, position ->

                if (view.id == R.id.tv_remark) {

                    hintDialog(data[position].description ?: "", {})

                }
            }

            rvLocus.initLinerDecoration(space = 0F, adapter = this)


        }



        rvWarehousing.initGridDecoration(
            spanCount = 5,
            space = 8f,
            adapter = warehousingAdapter,
            headFootSpace = 15F

        )
        rvLocation.initGridDecoration(
            spanCount = 5, space = 8f, adapter = locationAdapter, headFootSpace = 15F
        )


    }

    override fun createObserver() {
        super.createObserver()
        val notifyAndFinish: (ApiResponseNoData) -> Unit = {

            mViewModel.viewModelScope.launch {

                eventViewModel.onOrderChangeEvent.value = 0
                delay(300L)
                navigateUp()
            }
        }
        mViewModel.result.observer(this) {


            mDatabind.setData(it)
        }

        orderViewModel.deleteNotify.observer(this, notifyAndFinish)
        orderViewModel.notify.observer(this, notifyAndFinish)


    }

    @SuppressLint("SetTextI18n")
    private fun FragmentOrderDetailBinding.setData(it: OrderDetailResponse) {


        it.run {

            form?.run {

                locusAdapter.setNewInstance(ways)



                stvStart.setCenterString(start_address)
                stvEnd.setCenterString(end_address)
                stvName.setCenterString(names)
                stvNum.setCenterString(nums)
                stvWeight.setCenterString(weights)
                stvVolume.setCenterString(volume)

                stvContainerQuantity.setCenterString(nums2?.ifBlank { nums })

                stvTypeOfContainer.setCenterString(rules2?.ifBlank { rules })

                stvPackage.setCenterString(packets)

                stvSpecification.setCenterString(rules)
                stvType.setCenterString(types)


                stvDate.run {
                    isGone = sent_date.isNullOrBlank() || sent_date == "1"
                    setCenterString(
                        TimeUtils.millis2String(
                            (sent_date?.ifBlank { "0" }?.toLong() ?: 0L) * 1000,
                            "yyyy.MM.dd"
                        )
                    )
                }
                stvBonded.run {
                    isGone = add_service1.isNullOrBlank()
                    setCenterString(add_service1)
                }
                stvService.run {
                    isGone = add_service2.isNullOrBlank()
                    setCenterString(add_service2)
                }


                stvClaimGoods.run {
                    isGone = type == 0
                    setCenterString(if (type == 1) "集装箱取货" else "平板车取货")
                }

                stvTransportation.isGone = sent_type.isNullOrBlank()
                val sentWay = sent_type?.let {
                    StringBuilder().apply {
                        if (it.contains("1")) {
                            append("陆运,")
                        }
                        if (it.contains("2")) {
                            append("海运,")
                        }
                        if (it.contains("3")) {
                            append("铁路运,")
                        }
                        if (it.contains("4")) {
                            append("与客服协商")
                        }
                    }

                }

                sentWay?.run {

                    if (endsWith(",")) {
                        deleteAt(lastIndex)
                    }

                    stvTransportation.setCenterString(toString())
                }


            }
            storage?.run {

                if (isNotEmpty()) {
                    first { it.id == form?.sid1 }.isSelected = true
                    warehousingAdapter.setNewInstance(this)

                }
            }
            storage_son?.run {
                if (isNotEmpty()) {
                    first { it.id == form?.sid2 }.isSelected = true
                    locationAdapter.setNewInstance(this)
                }
            }


            order?.run {

                mViewModel.ewm = ewm ?: ""


                stvAdditionalServices.run {

                    isGone = zjfw.isNullOrBlank()
                    setCenterString(zjfw)
                }
                stvGoodsName.run {
                    isGone = goods_name.isNullOrBlank()
                    setCenterString(goods_name)
                }
                stvLeaseTime.run {
                    isGone = times.isNullOrBlank()
                    setCenterString(times)
                }
                stvRentalArea.run {
                    isGone = mianji.isNullOrBlank()
                    setCenterString(mianji)
                }

                tvOrderNum.text = "订单编号：${trade_no ?: ""}"

                tvDate.text =
                    "下单日期：${
                        TimeUtils.millis2String(
                            (create_time?.toLong() ?: 0L) * 1000,
                            "yyyy.MM.dd"
                        )
                    }"


                tvContainerNo.run {
                    isGone = box_no.isNullOrEmpty()
                    text = "集装箱号：${box_no}"
                }

                tvBoxReceive.run {
                    isGone = box_receive.isNullOrEmpty()
                    text = "提单号：${box_receive}"

                }

                when (status) {


                    STATUS_TO_SIGN_UP -> {// 签约
                        flowTagAdapter.addTags(
                            arrayOf(
                                BT_SIGN_UP_ENTRANCE,
                                BT_CANCEL
                            )
                        )
                    }


                    STATUS_FOR_THE_PAYMENT -> {

                        flowTagAdapter.addTags(
                            mutableListOf<String?>().apply {

                                if (mViewModel.type == 0) {
                                    add(BT_SIGNED)
                                }
                                add(BT_CANCEL)

                            }.toTypedArray()
                        )

                        showWarehousing()

                    }
                    STATUS_TO_START -> {

                        flowTagAdapter.addTags(
                            mutableListOf<String?>().apply {


                                if (mViewModel.type == 0) {
                                    add(BT_SIGNED)
                                    add(BT_TRAJECTORY)
//                                add(BT_CONFIRM_THE_RECEIPT_OF_GOODS)

                                }

                            }.toTypedArray()

                        )
                        showWarehousing()

                    }
                    STATUS_UNDERWAY -> {

                        flowTagAdapter.addTags(
                            mutableListOf<String?>().apply {

                                if (mViewModel.type == 0) {
                                    add(BT_SIGNED)
                                    add(BT_TRAJECTORY)
                                    add(BT_CONFIRM_THE_RECEIPT_OF_GOODS)

                                } else {
                                    add(BT_CONFIRM_COMPLETED)
                                }

                            }.toTypedArray()
                        )


                    }
                    STATUS_COMPLETED -> {
                        flowTagAdapter.addTags(
                            mutableListOf<String?>().apply {

                                if (mViewModel.type == 0) {
                                    add(BT_SIGNED)
                                    add(BT_TRAJECTORY)
                                }
                                add(BT_DELETE)

                            }.toTypedArray()
                        )

                    }


                    else -> {

                    }
                }


                tvPrice.text = "￥$price"


                val gone1 = {
                    stvStart.gone()
                    stvEnd.gone()

//                    stvDate.gone()
//                    stvBonded.gone()
//                    stvClaimGoods.gone()
//                    stvTransportation.gone()
//                    stvService.gone()

                }

                val weightAndVolume = { visible: Boolean ->

                    stvWeight.isVisible = visible
                    stvVolume.isVisible = visible


                    stvPackage.isGone = visible
                    stvType.isGone = visible
                    stvSpecification.isGone = visible
                }

                val changeLeft = {
                    stvSpecification.setLeftString("货物规格")
                    stvNum.setLeftString("货物数量")
                }
                when (form_type) {
                    IN_FORM -> {
                        weightAndVolume.invoke(true)
                        stvLocusTitle.visible()

                    }
                    OUT_FORM -> {
                        weightAndVolume.invoke(true)
//                        stvClaimGoods.gone()
                        stvLocusTitle.visible()
                    }
                    SELF_FORM -> {

                        stvType.gone()
                        stvNum.visible()
//                        stvDate.gone()
//                        stvBonded.gone()
//                        stvService.gone()
                    }
                    PASS_FORM -> {
                        stvLocusTitle.gone()

                        llContainer2.gone()
                        gone1()


                        stvImportAndExport.run {
                            setCenterString(if (form?.imorex == 1) "进口" else "出口")

                            isGone = form?.imorex == null || form?.imorex == 0

                        }
                        stvOriginalPlace.run {
                            setCenterString(form?.start_address)
                            isGone = form?.start_address.isNullOrBlank()
                        }

                        weightAndVolume.invoke(false)

                    }
                    STORAGE_FORM2 -> {
                        llContainer.gone()
                        llContainer3.gone()
                        llContainer2.visible()

                    }
                    STORAGE_FORM1 -> {
                        llContainer.gone()
                        llContainer3.visible()
                    }
                    STORAGE_FORM3 -> {
                        changeLeft()
                        gone1()
                        llContainer2.visible()
                    }
                    STORAGE_FORM4 -> {
                        changeLeft()
                        stvName.gone()
                        weightAndVolume.invoke(false)
                        gone1()
                        stvStart.visible()
                        stvEnd.visible()

                    }
                    "" -> {

                    }
                    else -> {
                        llContainer.gone()
                    }
                }

                if (CacheUtil.isDriver) {
                    gone1()
                    stvStart.visible()
                    stvEnd.visible()
                }
            }


        }




        clBg.visible()

    }


    override fun initData() {
        super.initData()
        arguments?.run {
            mViewModel.id = getInt("id")
            orderViewModel.id = mViewModel.id
            mViewModel.type = getInt("type")

        }


    }

    private fun showWarehousing() {

        mDatabind.run {

            stvWeight.gone()
            stvVolume.gone()

            stvPackage.visible()
            stvSpecification.visible()
            stvType.visible()
        }

    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.order_show()
    }

    companion object {


        const val IN_FORM = "in_form"   //进口表单
        const val OUT_FORM = "out_form" // 出口表单
        const val SELF_FORM = "self_form"  // 用户发布表单
        const val PASS_FORM = "pass_form"  //报关报税表单
        const val STORAGE_FORM1 = "storage_form1"  //园区仓储表单
        const val STORAGE_FORM2 = "storage_form2"  //吊具装卸箱表单
        const val STORAGE_FORM3 = "storage_form3"   //场地装卸其他表单
        const val STORAGE_FORM4 = "storage_form4"  //短途运输表单
    }
}